package com.cykj.page05.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @BelongsProject: hand-tomcat
 * @BelongsPackage: com.cykj.page01.util
 * @Author: 阿隆
 * @CreateTime: 2025-11-01 14:31
 * @Description: TODO
 * @Version: 1.0
 */
public class DruidDataSourceUtils {

    private static DruidDataSource druidDataSource;

    private DruidDataSourceUtils() {
    }


    static {
        try {
            //1.加载配置文件获取配置信息
            Properties prop = new Properties();
            prop.load(new FileInputStream("config/druid.properties"));

            //2.根据配置信息创建德鲁伊连接池
            druidDataSource = new DruidDataSource();

            druidDataSource.configFromPropety(prop);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    /**
     * @Description: 获取连接
     * @Param: []
     * @return: com.alibaba.druid.pool.DruidPooledConnection
     */
    public static DruidPooledConnection getConn() {
        try {
            return druidDataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }


    /**
     * @Description: 归还连接
     * @Param: [conn]
     * @return: void
     */
    public static void giveConn(DruidPooledConnection conn) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }


    /**
     * @Description: 释放资源
     * @Param: [ps, rs]
     * @return: void
     */
    public static void releaseResource(PreparedStatement ps, ResultSet rs) {

        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        try {
            if (ps != null) {
                ps.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }


}
